from typing import Optional
from fastapi import FastAPI, HTTPException, Path, Query
from pydantic import BaseModel
import uvicorn

# 创建app对象
app = FastAPI()


# 创建数据模型
class Book(BaseModel):
    title: str
    author: str
    price: float
    description: Optional[str] = "这是一本好书。"


# 测试数据
books_db = [
    {"id": 1, "title": "看漫画学Python", "author": "关东升", "price": 29.99},
    {"id": 2, "title": "杀死一只知更鸟", "author": "Harper Lee", "price": 19.99},
    {"id": 3, "title": "Python从小白到大牛", "author": "关东升", "price": 49.99},
    {"id": 4, "title": "漫画Java", "author": "关东升", "price": 39.99},
]


# 路由函数
@app.put("/books/{book_id}")
def update_book(
    book_id: int = Path(..., deprecated="书籍ID"),
    book: Book = None,
    q: str = Query(None, description="查询参数"),
):
    for item in books_db:
        # 检查指定ID的书籍是否存在
        book_data = None
        for item in books_db:
            if item["id"] == book_id:
                book_data = item
                break
        if book_data is None:  # 没有找到数据
            raise HTTPException(status_code=404, detail="图书没有找到")
        # 如果请求体存在数据，更新图书信息
        if book is not None:
            book_data.update(book.dict())

        # 如果请参数存在，更新图书信息
        if q is not None:
            book_data.update({"query": q})

        # 返回图书信息
        return {"book_id": book_id, "book": book_data}


if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
